package net.guerlab.sdk.anubis.accesstoken;

import net.guerlab.sdk.anubis.client.AnubisClient;
import net.guerlab.sdk.anubis.request.AccessTokenRequest;
import net.guerlab.sdk.anubis.response.AccessTokenResponse;

/**
 * AccessToken管理<br>
 * 默认使用{@link net.guerlab.sdk.anubis.accesstoken.AccessTokenMemoryStorage}作为AccessToken的储存实现<br>
 * 在分布式环境中请自行实现集中的储存实现
 * 
 * @author guer
 *
 */
public class AccessTokenManager {

    private static final AccessTokenManager INSTANCE;

    /**
     * AccessToken储存接口
     */
    private AccessTokenStorage storage = new AccessTokenMemoryStorage();

    /**
     * 蜂鸟开放平台请求客户端接口
     */
    private AnubisClient client;

    static {
        INSTANCE = new AccessTokenManager();
    }

    private AccessTokenManager() {
    }

    /**
     * 获取AccessToken管理实例
     * 
     * @return AccessToken管理实例
     */
    public static AccessTokenManager instance() {
        return INSTANCE;
    }

    /**
     * 返回 AccessToken储存接口
     *
     * @return AccessToken储存接口
     */
    public AccessTokenStorage getStorage() {
        return storage;
    }

    /**
     * 设置AccessToken储存接口
     *
     * @param storage
     *            AccessToken储存接口
     */
    public void setStorage(
            AccessTokenStorage storage) {
        if (storage == null) {
            return;
        }
        this.storage = storage;
    }

    /**
     * 获取AccessToken
     * 
     * @return AccessToken
     */
    public String getAccessToken() {
        if (storage == null) {
            return null;
        }

        String accessToken = storage.getAccessToken();

        if (accessToken == null && client != null) {
            AccessTokenRequest request = new AccessTokenRequest();

            AccessTokenResponse response = client.execute(request);

            storage.put(response.getData());

            accessToken = storage.getAccessToken();
        }

        return accessToken;
    }

    /**
     * 返回 蜂鸟开放平台请求客户端接口
     *
     * @return 蜂鸟开放平台请求客户端接口
     */
    public AnubisClient getClient() {
        return client;
    }

    /**
     * 设置蜂鸟开放平台请求客户端接口
     *
     * @param client
     *            蜂鸟开放平台请求客户端接口
     */
    public void setClient(
            AnubisClient client) {
        this.client = client;
    }
}
